const util = require('../utils/connection');

module.exports = {
  /**
   * 根据code查询对应对象的ID
   * @param code
   * @return {Promise<any>}
   */
  selectIdByCode: function(code) {
    return new Promise(async resolve => {
      const connection = await util.getConnection();
      connection.query('select id from dict where code = ?', code, async function (error, results) {
        connection.release();
        if (error) throw error;
        resolve({ data: (results[0] || {}).id });
      });
    });
  },
  /**
   * 根据对应的Code查询对应子级列表
   * @param parentCode
   * @return {Promise<any>}
   */
  selectByParentCode: function (parentCode) {
    return new Promise(async resolve => {
      const connection = await util.getConnection();
      const { data } = await this.selectIdByCode(parentCode);
      connection.query('select code, name from dict where parent_id = ?', data, function (error, results) {
        connection.release();
        if (error) throw error;
        resolve({ data: results });
      });
    });
  }
};
